#include <iostream>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include "Task.hpp"

using namespace std;
#define PROCESS_NUM 5

int WaitCommand(int waitFd, bool &quit)
{
    uint32_t command = 0;
    ssize_t s = read(waitFd, &command, sizeof(command));
    if (s == 0)
    {
        quit = true;
        return -1;
    }
    assert(s == sizeof(uint32_t));

    return command;
}

void SendAndWakeUp(pid_t id, int fd, uint32_t task)
{
    write(fd, &task, sizeof(task));
    cout << "call process " << id << "execute" << desc[task] << "through" << fd << endl;
}

int main()
{
    load();
    vector<pair<pid_t, int>> slots;
    for (int i = 0; i < PROCESS_NUM; i++)
    {
        // 创建管道
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n != -1);
        (void)n;

        pid_t id = fork();
        assert(id != -1);

        if (id == 0)
        {
            // 子进程:读取任务
            close(pipefd[1]);
            while (true)
            {
                bool quit = false;
                // 等命令
                int command = WaitCommand(pipefd[0], quit);
                if (quit)
                    break;

                // 执行命令
                if (command >= 0 && command < TaskSize())
                {
                    callbacks[command]();
                }
                else
                {
                    cout << "非法亲求" << endl;
                }
            }

            exit(1);
        }

        // 父进程:进行写入
        close(pipefd[0]);
        slots.push_back(pair<pid_t, int>(id, pipefd[1]));
    }

    // 派发任务
    srand((unsigned int)time(nullptr) ^ getpid());
    while (true)
    {
        // 选择任务
        int task = rand() % TaskSize();
        // 选择进程
        int ProcId = rand() % slots.size();
        // 布置任务
        SendAndWakeUp(slots[ProcId].first, slots[ProcId].second, task);
        sleep(1);
    }

    // 关闭fd
    for (const auto &slot : slots)
    {
        close(slot.second);
    }

    //回收所有子进程
    for (const auto &slot : slots)
    {
        waitpid(slot.first,nullptr,0);
    }
}
